#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include "Init.hpp"
#include "Log.hpp"

extern Log lg;
// Log lg;
Init init;

class Task
{
public:
    Task(int fd, const std::string &client_ip, uint16_t client_port)
        : fd_(fd), client_ip_(client_ip), client_port_(client_port)
    {
    }

    void Run()
    {
        char buff[4096]; // 可设置大一些

        ssize_t sz = read(fd_, buff, sizeof(buff));
        if (sz > 0)
        {
            buff[sz] = 0;
            std::cout << "client say# key: " << buff << std::endl;
            std::string res = init.Translation(buff);
            // std::string res = "snow";
            sz = write(fd_, res.c_str(), res.size());
            if (sz < 0)
                lg(Warning, "Task, write error, errno: %d, error string: %s", errno, strerror(errno));
        }
        else if (sz == 0)
        {
            // 为了美观，不再输出消息
            //  std::cout << "[" << client_ip << ":" << client_port << "]" << "quit" << std::endl;
            lg(Info, "[%s:%d] quit, sockfd: %d", client_ip_.c_str(), client_port_, fd_);
        }
        else
        {
            lg(Warning, "Task, read error, errno: %d, error string: %s", errno, strerror(errno));
        }

        close(fd_);
    }

    void operator()()
    {
        Run();
    }

private:
    int fd_;
    std::string client_ip_;
    uint16_t client_port_;
};